package Controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import ModelBean.CartDetailForm;
import ModelBean.NodeCategory;
import ModelBean.RegisterBean;
import ModelBean.Tag;
import POJO.Cart;
import POJO.CartDetail;
import POJO.Product;
import POJO.ProductDetail;
import Service.HomeService;
import Service.MailService;
import ServiceImp.CreateData;

@Controller
@Scope("request")
public class HomeController {

	@Autowired
	private MailService mailService;

	@Autowired
	private HomeService homeService;

	@Autowired
	private CreateData createData;

	@Autowired
	private Cart cart;

	@ModelAttribute("cartUser")
	public Cart getCart() {
		Cart cartUser = homeService.getCart();
		if (cartUser == null) {
			System.out.println("cart user null");
			return cart;
		} else {
			for (CartDetail detail : cart.getCartDetails()) {
				boolean flag = true;
				for (CartDetail d : cartUser.getCartDetails()) {
					if (d.getProductDetail().getProductDetailId() == detail
							.getProductDetail().getProductDetailId()) {
						flag = false;
					}
				}
				if (flag) {
					CartDetail cartdetail = new CartDetail(detail.getCount(),
							detail.getSellPrice(), new Date(), cartUser,
							detail.getProductDetail());
					homeService.storeCartDetail(cartdetail);
				}

			}
			cart.getCartDetails().clear();
		}
		System.out.println("cart user " + cartUser.getCartDetails().size());
		return homeService.getCart();
	
	}

	@ModelAttribute("newmodel")
	public NodeCategory getMenu() {
		// System.out.println("newmodel=================");
		return homeService.createTreeMenu();
		//return null;
	}

	@RequestMapping("/home")
	public ModelAndView showInfo() {
		Map<String, Object> model = new HashMap<String, Object>();

		//createData.generateData();

		model.put("productDiscount", homeService.getProductDiscount(8));
		model.put("productNew", homeService.getProductNew(8));

		return new ModelAndView("home", model);
	}

	@RequestMapping(value = "/detail", method = RequestMethod.GET)
	public ModelAndView showDetail(@RequestParam("id") int id) {
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("productDetail", homeService.getProductById(id));
		model.put("count", homeService.getCountInStore(id));
		model.put("types", homeService.getTypes());
		model.put("navi", homeService.createNavi(id, 2));

		return new ModelAndView("detail", model);
	}

	@RequestMapping(value = "/detailcategory", method = RequestMethod.GET)
	public ModelAndView showDetailCategory(@RequestParam("id") int id) {
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("navi", homeService.createNavi(id, 1));
		model.put("category", homeService.getCategoryById(id));
		return new ModelAndView("detailcategory", model);
	}

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public ModelAndView login(
			@RequestParam(value = "error", required = false) String error,
			@RequestParam(value = "logout", required = false) String logout,
			HttpServletRequest request) {
		Map<String, Object> model = new HashMap<String, Object>();
		// System.out.println("login");
		return new ModelAndView("login", model);
	}

	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public ModelAndView registerRender(
			@ModelAttribute("registerInfo") RegisterBean register,
			BindingResult result) {
		// System.out.println("regsiter GET method " +register.getEmail());
		Map<String, Object> model = new HashMap<String, Object>();
		return new ModelAndView("register", model);
	}

	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public String register(
			@ModelAttribute("registerInfo") @Valid RegisterBean register,
			BindingResult result, Model m) {
		//System.out.println("register POST method");
		if (result.hasErrors())
			return "register";
		homeService.createUser(register);
		return "redirect:register.html";
	}

	@RequestMapping(value = "/addToCart", method = RequestMethod.GET)
	public @ResponseBody String addToCart(@RequestParam("id") Integer id) {
		ProductDetail detail = homeService.getProductById(id);
		cart.addProductDetail(detail);
		if (homeService.getUserRole().equals("User")) {
			// homeService.storeCart(getCart());
		}
		return String.valueOf(cart.getCartDetails().size());
	}

	@RequestMapping(value = "/loadheader", method = RequestMethod.GET)
	public @ResponseBody String loadHeader() {
		if (homeService.getUserRole().equals("Admin")) {
			return "<a href=\"admin/admin.html\">Admin Panel</a> <a href=\"javascript:formSubmit()\">Logout</a>";
		} else if (homeService.getUserRole().equals("User")) {
			return "<a href=\"myaccount.html\">My Account</a> <a href=\"javascript:formSubmit()\">Logout</a> <a href=\"cart.html\">My Cart</a>";
		}

		return "<a href=\"login.html\">Login</a> <a href=\"register.html\">Register</a> <a href=\"cart.html\">My Cart</a>";
	}

	@RequestMapping(value = "/terms", method = RequestMethod.GET)
	public ModelAndView terms() {		
		Map<String, Object> model = new HashMap<String, Object>();
		return new ModelAndView("terms", model);
	}
	
	@RequestMapping(value = "/sendEmail", method = RequestMethod.GET)
	public String sendEmail() {		
		
		mailService.sendMail("ducmanhitus@gmail.com",
	    		   "phuochung2807@gmail.com",
	    		   "Testing123", 
	    		   "Testing only \n\n Hello Spring Email Sender");
		
		return "redirect:home.html";
	}
	
	@RequestMapping(value = "/cart", method = RequestMethod.GET)
	public String loadCart(Model m) {
		CartDetailForm cartDetailForm = new CartDetailForm();
		cartDetailForm.setCartDetails(new LinkedList<CartDetail>(getCart()
				.getCartDetails()));
		m.addAttribute("cartDetailForm", cartDetailForm);
		return "cart";
	}

	@RequestMapping(value = "/deleteItemInCart", method = RequestMethod.GET)
	public String deleteItemInCart(@RequestParam("id") int id) {
		if (homeService.getCart() == null) {
			CartDetail detail = null;
			for (CartDetail d : cart.getCartDetails()) {
				if (d.getCartDetailId() == id) {
					detail = d;
				}
			}
			cart.getCartDetails().remove(detail);
		} else {
			homeService.deleteCartDetail(id);
		}

		return "redirect:cart.html";
	}

	@RequestMapping(value = "/checkout", method = RequestMethod.POST)
	public ModelAndView save(
			@ModelAttribute("cartDetailForm") CartDetailForm cartDetailForm) {
		Cart c = getCart();
		for (int i = 0, n = cartDetailForm.getCartDetails().size(); i < n; i++) {
			for (CartDetail cartDetail : c.getCartDetails()) {

				if (cartDetail.getProductDetail().getProductDetailId() == cartDetailForm
						.getCartDetails().get(i).getProductDetail()
						.getProductDetailId()) {
					cartDetail.setCount(cartDetailForm.getCartDetails().get(i)
							.getCount());
					if (homeService.getCart() != null)
						homeService.storeCartDetail(cartDetail);
				}
			}
		}

		if (homeService.getCart() != null)
			return new ModelAndView("home");
		else
			return new ModelAndView("redirect:register.html");
	}

	@RequestMapping(value = "/getTags", method = RequestMethod.GET)
	public @ResponseBody List<Tag> getTags(
			@RequestParam("tagName") String tagName) {
		System.out.println("request");
		return simulateSearchResult(tagName);

	}

	private List<Tag> simulateSearchResult(String tagName) {

		List<Tag> result = new ArrayList<Tag>();

		// iterate a list and filter by tagName
		for (Tag tag : homeService.getAllTag()) {
			if (tag.getTagName().contains(tagName)) {
				result.add(tag);
				System.out.println("add result");
			}
		}

		return result;
	}

	@RequestMapping(value = "/search", method = RequestMethod.GET)
	public String Search(@RequestParam("search") String searchString, Model model) {
		System.out.println("search "+searchString);
		List<Product> ps = null;
		if (searchString != null) {
			ps = homeService.getAllProductDetailByTag(searchString);
			model.addAttribute("keyword", searchString);
			model.addAttribute("products", ps);
		}

		return "search";
	}
}
